<template>
  <div>
    <div
      @click="changeOn"
      class="music"
      :class="isOff?'isOff':'isOn'"
    ></div>
    <audio
      id="audio"
      :src="require('../../../public/static/audio/bgm.mp3')"
      loop
      autoplay
    ></audio>
  </div>
</template>
<script>
export default {
  data () {
    return {
      isOff: false
    }
  },
  components: {},
  created () {
  },
  mounted () {
    // 自动播放音乐效果，解决微信自动播放问题
    document.addEventListener('touchstart', this.audioAutoPlay, false);
    document.addEventListener('WeixinJSBridgeReady', this.audioAutoPlay, false);
    let oAudio = document.querySelector("#audio");
    oAudio.onended = function () {//播放完毕，重新循环播放
      oAudio.load();
      oAudio.play();
    }
  },
  methods: {
    changeOn () {
      let oAudio = document.querySelector("#audio");
      if (this.isOff) {
        oAudio.play();//开始播放     
      } else {
        oAudio.pause();//暂停播放 
      }
      this.isOff = !this.isOff;
    },
    audioAutoPlay () {
      let audio = document.getElementById('audio');
      this.isOff = false;
      audio.play();
      document.removeEventListener('touchstart', this.audioAutoPlay);
    }
  }
}
</script>
<style lang="less" scoped>
.music {
  position: fixed;
  bottom: 10px;
  right: 10px;
  z-index: 2000;
  width: 1.3rem;
  height: 1.3rem;
}
.isOn {
  animation: rotating 1.2s linear infinite;
  background: url("./../../base/music/musicOn.png") no-repeat;
  background-size: 100%;
}
.isOff {
  background: url("./../../base/music/musicOn.png") no-repeat;
  background-size: 100%;
}
@keyframes rotating {
  from {
    -webkit-transform: rotate(0);
  }
  to {
    -webkit-transform: rotate(360deg);
  }
}
</style>